package json

import (
	log "ac-common-go/glog"
	"ac-julink/tool/data"
	"encoding/json"
	"strconv"
	"strings"
)

// buildJsonCmdRet 构建CmdRst的JSON返回值
func buildJsonCmdRet(err int, result string) string {
	type cmdRst struct {
		Err    int    `json:"err"`
		Result string `json:"result"`
	}
	cmdret, _ := json.Marshal(cmdRst{err, result})
	result = string(cmdret)
	return result
}

// 通信模块消息上报查询消息处理
// ParseMsgId 解析消息ID
func ParseMsgId(jsonStr string) (msgid int, err error) {
	log.Infof("ParseMsgId:", jsonStr)
	type parseid struct {
		MessageId int `json:"id"`
	}
	var m parseid
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		msgid = m.MessageId
	}
	return msgid, err
}

// ParseAuthMsg 解析设备认证消息101
func ParseAuthMsg(jsonStr string) (wifiid, wifiver string, devicever []data.DeviceVer, protVer string, err error) {
	log.Infof("ParseAuthMsg:%s", jsonStr)
	type parseAuth struct {
		MessageId int              `json:"id"`
		WifiId    string           `json:"wid"`
		WifiVer   string           `json:"ver"`
		DevVer    []data.DeviceVer `json:"DevVer"`
		ProtVer   string           `json:"ProtVer"`
	}
	var m parseAuth
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		wifiid = strings.ToLower(m.WifiId)
		if strings.Contains(m.WifiVer, "\n") {
			wifiver = strings.Replace(m.WifiVer, "\n", "", -1)
		} else {
			wifiver = m.WifiVer
		}
		devicever = m.DevVer
	}
	return wifiid, wifiver, devicever, m.ProtVer, err
}

// ParseMsgKey 解析密钥交换消息102
func ParseMsgKey(jsonStr string) (token string, err error) {
	type parseKey struct {
		Token string `json:"token"`
	}
	var m parseKey
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		token = m.Token
	}
	return token, err
}

// ParseMsgConfig 解析系统参数获取消息103
func ParseMsgConfig(jsonStr string) (token string, err error) {
	type parseConfig struct {
		Token string `json:"token"`
	}
	var m parseConfig
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		token = m.Token
	}
	return token, err
}

// ParseMsgControl 解析指令结果消息201
func ParseMsgControl(jsonStr string) (_token, _result, _status string, _seq int, _err, _devtype int, _cmdver int, _cmdResult []data.CmdExecResult, err error) {
	type parseControl struct {
		Token  string `json:"token"`
		Seq    int    `json:"seq"`
		Err    int    `json:"err"`
		Type   int    `json:"type"`
		Cmdver int    `json:"cmdversion"`
		Result string `json:"result"`
	}
	var m parseControl
	err = json.Unmarshal([]byte(jsonStr), &m) //解析外层json
	if err != nil {
		log.Errorf("11%+v", err)
	} else {
		_token = m.Token
		_seq = m.Seq
		_err = m.Err
		_devtype = m.Type
		_cmdver = m.Cmdver
		_result = m.Result
		switch _devtype { //单设备
		case 0:
			{
				log.Info("========single device")
				_result = buildJsonCmdRet(_err, _result)
				if _err == 0 {
					_err = 1
				} else {
					_err = 8
				}
				type parseStatus struct {
					Status []struct {
						Msgtype    int    `json:"msgtype"`
						Msgsubtype int    `json:"msgsubtype"`
						Result     string `json:"result"`
					} `json:"status"`
				}
				var n parseStatus
				err = json.Unmarshal([]byte(jsonStr), &n)
				if err != nil {
					log.Errorf("%+v", err)
				} else {
					rawststus := make([]data.RawWGCommonStatus, len(n.Status))
					for i, mstatus := range n.Status {
						rawststus[i].SetMsgtype(mstatus.Msgtype)
						rawststus[i].SetMsgsubtype(mstatus.Msgsubtype)
						rawststus[i].SetRawstatus(mstatus.Result)
					}
					type Status struct {
						//首字母必须是大写
						Msgtype    int    `json:"msgtype"`
						Msgsubtype int    `json:"msgsubtype"`
						Result     string `json:"result"`
					}
					type statusret struct {
						Status_ []Status `json:"status"`
					}
					var _statusret statusret
					for _, ch := range rawststus {
						var _status Status
						_status.Msgtype = ch.GetMsgtype()
						_status.Msgsubtype = ch.GetMsgsubtype()
						_status.Result = ch.GetRawstatus()
						_statusret.Status_ = append(_statusret.Status_, _status)
					}
					status_rst, _ := json.Marshal(_statusret)
					_status = string(status_rst)
				}
			}
		case 1:
			{
				log.Info("========muit device")
				type parseStatus struct {
					Mutistatus []struct {
						Devid  string `json:"devid"`
						Err    int    `json:"err"`
						Result string `json:"result"`
					} `json:"mutiresult"`
				}

				var n parseStatus
				err = json.Unmarshal([]byte(jsonStr), &n)
				if err != nil {
					log.Errorf("parseMutistatus %+v", err)
				} else {
					_cmdResult = make([]data.CmdExecResult, len(n.Mutistatus))
					for i, info := range n.Mutistatus {
						_cmdResult[i].SetDeviceid(strings.ToLower(info.Devid))
						_cmdResult[i].SetRetmsg(info.Result)
						_cmdResult[i].SetRetno(info.Err)
						_cmdResult[i].SetRetmsg(buildJsonCmdRet(_cmdResult[i].GetRetno(), _cmdResult[i].GetRetmsg()))
						if _cmdResult[i].GetRetno() == 0 {
							_err = 1
						} else {
							_err = 8
						}
					}
				}
			}
		}
	}
	log.Info("<<<<=============ParseMsgControl")
	return _token, _result, _status, _seq, _err, _devtype, _cmdver, _cmdResult, err
}

// ParseMsgQuery 解析查询结果消息202
// 先按照30指令格式解析状态,失败再按照status:rawstatus格式解析
func ParseMsgQuery(jsonStr string) (token, status string, _err, seq int, devStatuslist []data.DeviceData, err error) {
	//		fmt.Println("ParseMsgQuery:", jsonStr)
	type parseQuery struct {
		Token string `json:"token"`
		Seq   int    `json:"seq"`
		Err   int    `json:"err"`
		Devid string `json:"devid"`
	}
	type parseStatus struct {
		Status []struct {
			Msgtype    int    `json:"msgtype"`
			Msgsubtype int    `json:"msgsubtype"`
			Result     string `json:"result"`
		} `json:"status"`
	}
	type Status struct {
		//首字母必须是大写
		Msgtype    int    `json:"msgtype"`
		Msgsubtype int    `json:"msgsubtype"`
		Result     string `json:"result"`
	}
	type statusret struct {
		Status_ []Status `json:"status"`
	}
	var m parseQuery
	var strStatus data.DeviceData
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		token = m.Token
		seq = m.Seq
		_err = m.Err
		//		strStatus.deviceid = strings.ToLower(m.Devid)
		strStatus.SetDeviceId(strings.ToLower(m.Devid))
		var n parseStatus
		err = json.Unmarshal([]byte(jsonStr), &n) //先按照30格式解析
		if err != nil {
			log.Infof("Invalid 30 Status, %+v", err)
			type parseRawstatus struct {
				RawStatus string `json:"status"`
			}
			var m parseRawstatus
			err = json.Unmarshal([]byte(jsonStr), &m)
			if err != nil {
				log.Errorf("parseRawstatus %+v", err)
			} else {
				var _statusret statusret
				_statusret = statusret{[]Status{{30, 0, "hAUAAhUAAAA="}, {102, 0, m.RawStatus}}}
				status_rst, _ := json.Marshal(_statusret)
				status = string(status_rst)
				//				fmt.Println("[parseRawstatus]: ", string(status_rst))
			}
		} else {
			rawstatus := make([]data.RawWGCommonStatus, len(n.Status))
			for i, mstatus := range n.Status {
				rawstatus[i].SetMsgtype(mstatus.Msgtype)
				rawstatus[i].SetMsgsubtype(mstatus.Msgsubtype)
				rawstatus[i].SetRawstatus(mstatus.Result)
			}
			var _statusret statusret
			for _, ch := range rawstatus {
				var _status Status
				_status.Msgtype = ch.GetMsgtype()
				_status.Msgsubtype = ch.GetMsgsubtype()
				_status.Result = ch.GetRawstatus()
				_statusret.Status_ = append(_statusret.Status_, _status)
			}
			status_rst, _ := json.Marshal(_statusret)
			status = string(status_rst)
		}
		//		strStatus.value = status
		strStatus.SetValue(status)
		devStatuslist = append(devStatuslist, strStatus)
	}
	return token, status, _err, seq, devStatuslist, err
}

// ParseMsgReset 解析重置消息
func ParseMsgReset(jsonStr string) (_token string, _seq int32, _err int32, err error) {
	type parseWifiReset struct {
		Token string `json:"token"`
		Seq   int32  `json:"seq"`
		Err   int32  `json:"err"`
	}
	var m parseWifiReset
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_err = m.Err
		_seq = m.Seq
	}
	return _token, _seq, _err, err
}

// ParseMsgQueryVer 解析版本查询消息301
func ParseMsgQueryVer(jsonStr string) (_token, _ver string, _type, _err int, err error) {
	type parseQueryVer struct {
		Token string `json:"token"`
		Type  int    `json:"type"`
		Ver   string `json:"ver"`
		Err   int    `json:"err"`
	}
	var m parseQueryVer
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_ver = m.Ver
		_type = m.Type
		_err = m.Err
	}
	return _token, _ver, _type, _err, err
}

// ParseMsgOtaResult 解析升级结果反馈消息302
func ParseMsgOtaResult(jsonStr string) (_token, _desc, _wifiVersion, _originVersion, _targetVersion string, _err, _resultCode, _policyId int, err error) {
	type parseOtaResult struct {
		Token           string `json:"token"`
		Err             int    `json:"err"`
		ResultCode      int    `json:"resultCode"`
		Desc            string `json:"desc"`
		PolicyId        int    `json:"policyId"`
		WifiVersion     string `json:"wifiVersion"`
		OriginalVersion string `json:"originalVersion"`
		TargetVersion   string `json:"targetVersion"`
	}
	var m parseOtaResult
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_err = m.Err
		_resultCode = m.ResultCode
		_desc = m.Desc
		_policyId = m.PolicyId
		_wifiVersion = m.WifiVersion
		_originVersion = m.OriginalVersion
		_targetVersion = m.TargetVersion

	}
	return _token, _desc, _wifiVersion, _originVersion, _targetVersion, _err, _resultCode, _policyId, err
}

// ParseMsgQueryOta 解析查询升级消息303
func ParseMsgQueryOta(jsonStr string) (_token, _wifiVer string, languageId int32, err error) {
	type parseQueryOta struct {
		Id         int32  `json:"id"`
		Token      string `json:"token"`
		WifiVer    string `json:"wifiVer"`
		LanguageId int32  `json:"languageId"`
	}
	var m parseQueryOta
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_wifiVer = m.WifiVer
		languageId = m.LanguageId
	}
	return _token, _wifiVer, languageId, err
}

// ParseMsgMcuUpgradeResult 解析升级结果反馈消息305
func ParseMsgMcuUpgradeResult(jsonStr string) (_token, _ver string, _type string, _errCode int, err error) {
	type parseMcuUpgradeResult struct {
		Token   string `json:"token"`
		Type    string `json:"type"`
		Ver     string `json:"ver"`
		ErrCode int    `json:"err"`
	}
	var m parseMcuUpgradeResult
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_errCode = m.ErrCode
		_type = m.Type
		_ver = m.Ver
	}
	return
}

// ParseMsgDevBind 解析设备绑定消息401
func ParseMsgDevBind(jsonStr string) (_token, _devid string, err error) {
	type parseDevBind struct {
		Token string `json:"token"`
		Devid string `json:"devid"`
	}
	var m parseDevBind
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("error:", err)
	} else {
		_token = m.Token
		_devid = m.Devid
	}
	return _token, _devid, err
}

// ParseMsgDevUnBind 解析设备绑定消息402
func ParseMsgDevUnBind(jsonStr string) (_token, _devid string, err error) {
	type parseDevUnBind struct {
		Token string `json:"token"`
		Devid string `json:"devid"`
	}
	var m parseDevUnBind
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_devid = m.Devid
	}
	return _token, _devid, err
}

// ParseMsgDevBindList 解析设备绑定列表请求消息403
func ParseMsgDevBindList(jsonStr string) (_token string, err error) {
	type parseDevBindList struct {
		Token string `json:"token"`
	}
	var m parseDevBindList
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
	}
	return _token, err
}

// ParseMsgGwHomeDevList 解析网关所属家庭下设备列表请求消息404
func ParseMsgGwHomeDevList(jsonStr string) (_token string, err error) {
	type parseGwHomeDevList struct {
		Token string `json:"token"`
	}
	var m parseGwHomeDevList
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
	}
	return _token, err
}

// ParseMsgDevExtInfoSave 解析设备扩展信息存储请求消息406
func ParseMsgDevExtInfoSave(jsonStr string) (_token, _devid, _extkey, _extinfo string, err error) {
	type parseDevExtInfoSave struct {
		Token  string `json:"token"`
		Devid  string `json:"devId"`
		Extkey string `json:"extkey"`
	}
	var m parseDevExtInfoSave
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_devid = m.Devid
		_extkey = m.Extkey
	}

	type parseExtInfo struct {
		ExtInfo []struct {
			ExtInfoValue string `json:"extInfoValue"`
			OprType      int    `json:"oprType"`
		} `json:"extInfo"`
	}

	var extInfo parseExtInfo
	err = json.Unmarshal([]byte(jsonStr), &extInfo)
	if err != nil {
		//		log.Errorf("%+v", err)
		log.Info("ExtInfo is string format !!")
		type parseExtInfoString struct {
			ExtInfo string `json:"extInfo"`
		}
		var m parseExtInfoString
		err = json.Unmarshal([]byte(jsonStr), &m)
		if err != nil {
			log.Errorf("%+v", err)
		} else {
			_extinfo = m.ExtInfo
		}
	} else {
		_extinfo = _extinfo + "["
		size := len(extInfo.ExtInfo)
		for i, ch := range extInfo.ExtInfo {
			_extinfo = _extinfo + "{\"extInfoValue\":"
			_extinfo = _extinfo + "\""
			_extinfo = _extinfo + ch.ExtInfoValue
			_extinfo = _extinfo + "\","
			_extinfo = _extinfo + "\"oprType\":"
			_extinfo = _extinfo + strconv.Itoa(ch.OprType)
			_extinfo = _extinfo + "}"
			if size > 1 && (size-i) > 1 {
				_extinfo = _extinfo + ","
			}
		}
		_extinfo = _extinfo + "]"
	}
	return _token, _devid, _extkey, _extinfo, err
}

// ParseMsgDevReset 解析设备重置请求消息407
func ParseMsgDevReset(jsonStr string) (_token string, _oprtype int, err error) {
	type parseDevReset struct {
		Token   string `json:"token"`
		OprType int    `json:"oprType"`
	}
	var m parseDevReset
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_oprtype = m.OprType
	}
	return _token, _oprtype, err
}

// ParseMsgHomeScenceInfo 解析网关所在家庭场景消息501
func ParseMsgHomeSceneInfo(jsonStr string) (_token string, err error) {
	type parseHomeSceneInfo struct {
		Token string `json:"token"`
	}
	var m parseHomeSceneInfo
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
	}
	return _token, err
}

// ParseMsgGetSceneInfo 解析ID场景信息查询消息502
func ParseMsgGetSceneInfo(jsonStr string) (_token string, _scene_list []int, _multconscenable int, err error) {
	type parseGetSceneInfo struct {
		Token          string `json:"token"`
		Multconscenble int    `json:"multconsc_enable"`
	}
	var m parseGetSceneInfo
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_token = m.Token
		_multconscenable = m.Multconscenble
	}
	type parseSceneId struct {
		SceneId []struct {
			Sceneid string `json:"sceneid"`
		} `json:"sceneids"`
	}
	var n parseSceneId
	err = json.Unmarshal([]byte(jsonStr), &n)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_scene_list = make([]int, len(n.SceneId))
		for i, ch := range n.SceneId {
			_scene_list[i], _ = strconv.Atoi(ch.Sceneid)
		}
	}
	return _token, _scene_list, _multconscenable, err
}

// ConfigDataResult 解析配置数据结果601
func ParseMsConfigDataResult(jsonStr string) (_id int, _token string, _seq int, _dataType string, _data string, _devid string, _err int, err error) {
	type parseConfigDataResult struct {
		Id       int    `json:"id"`
		Token    string `json:"token"`
		Seq      int    `json:"seq"`
		DataType string `json:"dataType"`
		Data     string `json:"data"`
		Devid    string `json:"devid"`
		Err      int    `json:"err"`
	}
	var m parseConfigDataResult
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("Unmarshal ParseMsConfigDataResult error: %+v", err)
	}

	return m.Id, m.Token, m.Seq, m.DataType, m.Data, m.Devid, m.Err, nil
}

// ParseMsgDevReset 解析设备配置数据上报
func ParseMsConfigDataReport(jsonStr string) (_id int, _token string, _seq int, _dataType, _data, _devid string, err error) {
	type parseConfigData struct {
		Id       int    `json:"id"`
		Token    string `json:"string"`
		Devid    string `json:"devid"`
		Seq      int    `json:"seq"`
		DataType string `json:"dataType"`
		Data     string `json:"data"`
	}
	var m parseConfigData
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("Unmarshal ParseMsConfigDataReport error: %+v", err)
	}

	return m.Id, m.Token, m.Seq, m.DataType, m.Data, m.Devid, nil
}

// ParseMsgStatusReport 解析设备状态上报消息901
func ParseMsgStatusReport(jsonStr string) (_token, _status string, _err, _type, _seq, _cmdver, _statusver int, _devstatuslist []data.DeviceData, err error) {
	type parseStatusReport struct {
		Token     string `json:"token"`
		Err       int    `json:"err"`
		Seq       int    `json:"seq"`
		StatusVer int    `json:"statusversion"`
		Cmdver    int    `json:"cmdversion"`
	}
	var m parseStatusReport
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_err = m.Err
		if _err != 0 { //_err!=0,表示状态上报异常
			return _token, _status, -1, _type, _seq, _cmdver, _statusver, _devstatuslist, err
		}
		_token = m.Token
		_cmdver = m.Cmdver
		_seq = m.Seq
		_statusver = m.StatusVer
	}
	//解析有无type字段,以及type的值.无字段或type=0表示单设备
	type parseStatusType struct {
		Type int `json:"type"`
	}
	var t parseStatusType
	err = json.Unmarshal([]byte(jsonStr), &t)
	if err != nil {
		log.Error("Status no type")
		_type = 0
	} else {
		_type = t.Type
		switch _type {
		case 0: //一对一设备
			{
				type parseStatus struct {
					Status []struct {
						Msgtype    int    `json:"msgtype"`
						Msgsubtype int    `json:"msgsubtype"`
						Result     string `json:"result"`
					} `json:"status"`
				}
				var n parseStatus
				err = json.Unmarshal([]byte(jsonStr), &n)
				if err != nil {
					log.Errorf("%+v", err)
				} else {
					rawststus := make([]data.RawWGCommonStatus, len(n.Status))
					for i, mstatus := range n.Status {
						rawststus[i].SetMsgtype(mstatus.Msgtype)
						rawststus[i].SetMsgsubtype(mstatus.Msgsubtype)
						rawststus[i].SetRawstatus(mstatus.Result)
					}
					type Status struct {
						//首字母必须是大写
						Msgtype    int    `json:"msgtype"`
						Msgsubtype int    `json:"msgsubtype"`
						Result     string `json:"result"`
					}
					type statusret struct {
						Status_ []Status `json:"status"`
					}
					var _statusret statusret
					for _, ch := range rawststus {
						var _status Status
						_status.Msgtype = ch.GetMsgtype()
						_status.Msgsubtype = ch.GetMsgsubtype()
						_status.Result = ch.GetRawstatus()
						_statusret.Status_ = append(_statusret.Status_, _status)
					}
					status_rst, _ := json.Marshal(_statusret)
					_status = string(status_rst)
				}
			}
		case 1: //一拖多设备
			{
				type parseMultStatus struct {
					Mutistatus []struct {
						Devid  string `json:"devid"`
						Status []struct {
							Msgtype    int    `json:"msgtype"`
							Msgsubtype int    `json:"msgsubtype"`
							Result     string `json:"result"`
						} `json:"status"`
					} `json:"status"`
				}

				var mult parseMultStatus
				err = json.Unmarshal([]byte(jsonStr), &mult)
				if err != nil {
					log.Errorf("error parseMultStatus ", err)
				} else {
					for i, ch := range mult.Mutistatus { //devid
						var strStatus data.DeviceData //{"devid":"","value":""}
						strStatus.SetDeviceId(ch.Devid)
						rawststus := make([]data.RawWGCommonStatus, len(mult.Mutistatus[i].Status))
						for j, mstatus := range mult.Mutistatus[i].Status { //status
							rawststus[j].SetMsgtype(mstatus.Msgtype)
							rawststus[j].SetMsgsubtype(mstatus.Msgsubtype)
							rawststus[j].SetRawstatus(mstatus.Result)
						}

						type Status struct {
							//首字母必须是大写
							Msgtype    int    `json:"msgtype"`
							Msgsubtype int    `json:"msgsubtype"`
							Result     string `json:"result"`
						}
						type statusret struct {
							Status_ []Status `json:"status"`
						}
						var _statusret statusret
						for _, ch := range rawststus {
							var _status Status
							_status.Msgtype = ch.GetMsgtype()
							_status.Msgsubtype = ch.GetMsgsubtype()
							_status.Result = ch.GetRawstatus()
							_statusret.Status_ = append(_statusret.Status_, _status)
						}
						status_rst, _ := json.Marshal(_statusret)
						_status = string(status_rst)
						strStatus.SetValue(_status)
						_devstatuslist = append(_devstatuslist, strStatus)
					}

				}
			}
		}
	}
	return _token, _status, _err, _type, _seq, _cmdver, _statusver, _devstatuslist, err
}

// ParseMsgStatusReport 解析设备状态上报消息903
func ParseMsgStatusReportUpdate(jsonStr string) (_token, _status string, _err, _type, _seq, _cmdver, _statusver int, _devstatuslist []data.DeviceData, err error) {
	type ParseStatus struct {
		Devid       string `json:"devid"`
		InnerStatus string `json:"status"`
	}
	type parseStatusReport struct {
		Token string `json:"token"`
		Err   int    `json:"err"`
		Seq   int    `json:"seq"`
		//StatusVer int    `json:"statusversion"`
		//Cmdver    int    `json:"cmdversion"`
		ParseStatus []ParseStatus `json:"status"`
	}

	var m parseStatusReport
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_err = m.Err
		if _err != 0 { //_err!=0,表示状态上报异常
			return _token, _status, -1, _type, _seq, _cmdver, _statusver, _devstatuslist, err
		}
		_token = m.Token
		//_cmdver = m.Cmdver
		_seq = m.Seq
		//_statusver = m.StatusVer
	}
	//解析有无type字段,以及type的值.无字段或type=0表示单设备
	type parseStatusType struct {
		Type int `json:"type"`
	}
	var t parseStatusType
	err = json.Unmarshal([]byte(jsonStr), &t)
	if err != nil {
		log.Error("Status no type")
		_type = 0
	} else {
		_type = t.Type
		switch _type {
		case 0: //一对一设备
			{
				for _, ch := range m.ParseStatus {
					/*i :=ch.InnerStatus.(map[string]interface{})
					jStr, err := json.Marshal(&i)
					if err != nil {
						fmt.Println(err)
					}
					_status = string(jStr)*/
					_status = ch.InnerStatus
					log.Infof("_status %s", _status)
				}

			}
		case 1: //一拖多设备
			{

				for _, ch := range m.ParseStatus { //devid
					var strStatus data.DeviceData //{"devid":"","value":""}
					strStatus.SetDeviceId(ch.Devid)
					/*i:=ch.InnerStatus.(map[string]interface{})
					jStr, err := json.Marshal(&i)
					if err != nil {
						fmt.Println(err)
					}
					strStatus.SetValue(string(jStr))*/
					strStatus.SetValue(ch.InnerStatus)
					_devstatuslist = append(_devstatuslist, strStatus)
				}

			}
		}
	}

	return _token, _status, _err, _type, _seq, _cmdver, _statusver, _devstatuslist, err
}

//通信模块消息响应,JSON数据组装
//func JsonQuaryOta() (jsonstr string, err error)

// MQ 消息解析
// MQParseMsgCmdControl 解析控制指令MQ消息,包括201和202指令
// Return:
//
//		_cmd:单设备指令或一拖多设备指令JSON串
//	 _type:0 单设备,1 多设备
func MQParseMsgCmdControl(jsonStr string) (_wifiid, _devid, _cmd string, _id, _seq, _cmdver, _type int, err error) {
	type MQparseCmd struct {
		Wifiid string `json:"wifiid"`
		Id     int    `json:"id"`
		Devid  string `json:"devid"`
		Seq    int    `json:"cmdno"`
		Cmdver int    `json:"cmdversion"`
	}
	var m MQparseCmd
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_wifiid = m.Wifiid
		_id = m.Id
		_seq = m.Seq
		_devid = m.Devid
		_cmdver = m.Cmdver

	}
	type MQCmd struct {
		Cmd string `json:"cmd"`
	}
	var n MQCmd
	err = json.Unmarshal([]byte(jsonStr), &n)
	if err != nil || strings.EqualFold(n.Cmd, "") { //一拖多设备指令

		type MQparseMutiCmd struct {
			Cmd []struct {
				Devid string `json:"deviceid"`
				Cmd   string `json:"cmd"`
			} `json:"cmdlist"`
		}
		var p MQparseMutiCmd
		err = json.Unmarshal([]byte(jsonStr), &p)
		if err != nil {
			log.Errorf("%+v", err)
		} else {
			muticmd := make([]data.RawWGCommonCmd, len(p.Cmd))
			for i, cmd := range p.Cmd {
				muticmd[i].SetDeviceId(strings.ToLower(cmd.Devid))
				muticmd[i].SetCom(cmd.Cmd)
			}

			type MultCmd struct {
				//首字母必须是大写
				Devid string `json:"deviceid"`
				Cmd   string `json:"cmd"`
			}
			type cmdRet struct {
				MultCmdRet []MultCmd `json:"cmdlist"`
			}
			var _cmdret cmdRet
			for _, ch := range muticmd {
				var _cmd MultCmd
				_cmd.Devid = ch.GetDeviceId()
				_cmd.Cmd = ch.GetCom()
				_cmdret.MultCmdRet = append(_cmdret.MultCmdRet, _cmd)
			}
			cmd_rst, _ := json.Marshal(_cmdret)
			_cmd = string(cmd_rst)
			_type = 1
		}
	} else { //一对一设备指令
		_cmd = n.Cmd
		_type = 0
	}
	return _wifiid, _devid, _cmd, _id, _seq, _cmdver, _type, err
}
func MQParseMsgConfigControl(jsonStr string) (_wifiid, _devid, _dataType, _data string, _id, _seq, _err int, err error) {
	type MQparseCmd struct {
		Wifiid   string `json:"wifiid"`
		Id       int    `json:"id"`
		Devid    string `json:"devid"`
		Seq      int    `json:"seq"`
		DataType string `json:"dataType"`
		Data     string `json:"data"`
		Err      int    `json:"err"`
	}
	var m MQparseCmd
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_wifiid = m.Wifiid
		_id = m.Id
		_seq = m.Seq
		_devid = m.Devid
		_dataType = m.DataType
		_data = m.Data
		_err = m.Err

	}
	return _wifiid, _devid, _dataType, _data, _id, _seq, _err, err
}

func MQParseMsgCommonControl(jsonStr string) (_wifiid, _data string, _id int, err error) {
	type MQparseCmd struct {
		Wifiid string `json:"wifiid"`
		Id     int    `json:"msgid"`
		Data   string `json:"data"`
	}
	var m MQparseCmd
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_wifiid = m.Wifiid
		_id = m.Id
		_data = m.Data

	}
	return _wifiid, _data, _id, err
}

// MQParseMsgOta 解析升级策略下发消息
func MQParseMsgOta(jsonStr string) (_wifiid, _wifiver, _url, _md5 string, _filesize, _updateflag, _policyId int, _versiondesc, _signature string, _targetedType int, err error) {
	type MQparseOta struct {
		Wifiid       string `json:"wifiid"`
		Wifiver      string `json:"wifi_version"`
		Url          string `json:"wifi_upgrade_url"`
		Filesize     int    `json:"file_size"`
		Md5          string `json:"checksum"`
		Updataflag   int    `json:"updateFlag"`
		VersionDesc  string `json:"versionDesc"`
		PolicyId     int    `json:"policyId"`
		Signature    string `json:"signature"`
		TargetedType int    `json:"targetedType"`
	}
	var m MQparseOta
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_wifiid = m.Wifiid
		_wifiver = m.Wifiver
		_url = m.Url
		_md5 = m.Md5
		_filesize = m.Filesize
		_updateflag = m.Updataflag
		_versiondesc = m.VersionDesc
		_policyId = m.PolicyId
		_signature = m.Signature
		_targetedType = m.TargetedType
	}
	return _wifiid, _wifiver, _url, _md5, _filesize, _updateflag, _policyId, _versiondesc, _signature, _targetedType, err
}

// MQParseMsgMcu 解析升级策略下发消息
func MQParseMsgMcu(jsonStr string) (_wifiid, _type, _ver, _md5, _checksum, _addr string, _filesize, _effectiveStart, _effectiveLen int, err error) {
	type MQparseMcu struct {
		OprType          int    `json:"oprType"`
		Wifiid           string `json:"wifiId"`
		DeviceId         string `json:"deviceId"`
		SubSystemCode    string `json:"subSystemCode"`
		SubSystemVersion string `json:"subSystemVersion"`
		UpgradeFileLen   string `json:"upgradeFileLen"`
		Md5Code          string `json:"md5Code"`
		CheckSum         string `json:"checkSum"`
		EffectiveStart   string `json:"effectiveStart"`
		EffectiveLen     string `json:"effectiveLen"`
		UpgradeFileAddr  string `json:"upgradeFileAddr"`
	}
	var m MQparseMcu
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_wifiid = m.Wifiid
		_type = m.SubSystemCode
		_ver = m.SubSystemVersion
		_filesize, _ = strconv.Atoi(m.UpgradeFileLen)
		_md5 = m.Md5Code
		_checksum = m.CheckSum
		_effectiveStart, _ = strconv.Atoi(m.EffectiveStart)
		_effectiveLen, _ = strconv.Atoi(m.EffectiveLen)
		_addr = m.UpgradeFileAddr
	}
	return
}

// MQParseMsgScene 解析场景指令消息
func MQParseMsgScene(jsonStr string) (_sceneId, _wifiId, _deviceId, _deviceType string, _wifiidlist []string, _optype, _exeType int, err error) {
	type MQSceneType struct {
		SceneId string `json:"sceneId"`
		Optype  int    `json:"opType"`
	}
	var m MQSceneType //首先解析场景指令类型
	err = json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_sceneId = m.SceneId
		_optype = m.Optype
		if _optype == 4 { //条件执行
			type SceneExeType struct {
				ExeType int `json:"exeType"`
			}
			var n SceneExeType //场景执行类型
			err = json.Unmarshal([]byte(jsonStr), &n)
			if err != nil {
				log.Errorf("%+v", err)
			} else {
				_exeType = n.ExeType
				if _exeType == 3 { //条件执行,触发条件设备信息
					type ConDevInfo struct {
						Wifiid  string `json:"wifiId"`
						DevId   string `json:"deviceId"`
						DevType string `json:"deviceType"`
					}
					type ConInfo struct {
						Coninfo ConDevInfo `json:"conditionDeviceInfo"`
					}
					var p ConInfo //设备条件信息
					err = json.Unmarshal([]byte(jsonStr), &p)
					if err != nil {
						log.Errorf("%+v", err)
					} else {
						_wifiId = p.Coninfo.Wifiid
						_deviceId = p.Coninfo.DevId
						_deviceType = p.Coninfo.DevType
					}
				}
			}
		}
		type wifiInfo struct {
			WifiidInfo string `json:"wifiid"`
		}
		type wifiList struct {
			WifiidList []wifiInfo `json:"wifiIdList"`
		}
		var q wifiList //设备列表
		err = json.Unmarshal([]byte(jsonStr), &q)
		if err != nil {
			log.Errorf("%+v", err)
		} else {
			for _, ch := range q.WifiidList {
				_wifiidlist = append(_wifiidlist, ch.WifiidInfo)
			}
		}
	}
	return _sceneId, _wifiId, _deviceId, _deviceType, _wifiidlist, _optype, _exeType, err
}
